// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境

const db = cloud.database()//引用云数据库
const canJu = db.collection("canju")
const account = db.collection("account")

// 云函数入口函数
// 残局函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  try {
    let thisCanju = await canJu.doc(event._id)
      .field({
        level: true,
        canPlay: true,
        win: true,
        openid: true,
        playInfo: true,
        progressTipsNum:true
      })
      .get()

    let author = await account.where({
      openid: thisCanju.data.openid
    }).get()

    thisCanju.data.userInfo = author.data[0].userInfo

    if (thisCanju.data.canPlay == false || thisCanju.data.win == true) {
      return {
        code: 'playFail',
        res: null
      }
    } else {
      const alreadyPlay = thisCanju.data.playInfo.some(obj => obj.openid == wxContext.OPENID)
      thisCanju.data.alreadyPlay = alreadyPlay
      delete thisCanju.data.openid
      delete thisCanju.data.playInfo
      return {
        code: 'getCanJuByIdOK',
        res: thisCanju.data
      }
    }
  } catch (error) {
    return {
      code: 'playFail',
      res: null
    }
  }
}
